package net.alan.modules.service.impl;

import net.alan.modules.bean.PageModel;
import net.alan.modules.bean.Result;
import net.alan.modules.bean.ResultUtil;
import net.alan.modules.handle.BaseExecption;
import net.alan.modules.service.IBaseService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;

import java.io.Serializable;
import java.util.List;

/**
 * Author 李岩飞
 * Email eliyanfei@126.com
 * 2017/11/24
 */
public abstract class BaseServiceImpl implements IBaseService {
    @Override
    public Page findAll(Class<?> cla, PageModel pageModel) {
        return getJpaRepository(cla).findAll(pageModel.getPageable());
    }

    @Override
    public <T> T getById(Class<? extends T> cla, Serializable id) {
        try {
            T t= (T) getJpaRepository(cla).getOne(id);
            t.toString();
            return t;
        } catch (Exception e) {
        }
        return null;
    }

    protected boolean isSame(Class<?> cla1, Class<?> cla2) {
        return cla1.isAssignableFrom(cla2);
    }

    @Override
    public Page findAll(Class<?> cla, PageModel pageModel, Sort.Direction direction, String field) {
        return getJpaRepository(cla).findAll(pageModel.getPageable(direction, field));
    }

    @Override
    public <T> List<T> findAll(Class<T> cla) {
        return getJpaRepository(cla).findAll();
    }

    @Override
    public void save(Class<?> cla,Object obj) throws BaseExecption {
        try {
            obj = getJpaRepository(cla).save(obj);
            afterSave(obj);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseExecption("数据保存错误"+e.getMessage());
        }
    }

    @Override
    public Result delete(Class<?> cla, Integer id) throws BaseExecption {
        try {
            getJpaRepository(cla).delete(id);
        } catch (Exception e) {
            throw new BaseExecption("删除异常");
        }
        return ResultUtil.success();
    }

    @Override
    public void update(Class<?> cla,Object obj) throws BaseExecption {
        try {
            obj = getJpaRepository(cla).save(obj);
        } catch (Exception e) {
            throw new BaseExecption("数据保存错误");
        }
    }

    public void afterDelete(Object obj) {
    }

    public void afterSave(Object obj) {
    }

    public void afterUpdate(Object obj) {
    }

    @Override
    public long count(Class<?> cla) {
        return getJpaRepository(cla).count();
    }
}
